#include<func.h>
#include<mysql/mysql.h>

typedef struct train_s
{
    int size;
    char buf[1024];
} train_t;

void get_filename(const char* path, char* filename, size_t size) {
    // 找到最后一个路径分隔符的位置
    char* pos = strrchr(path, '/');
    if (pos == NULL) {
        // 如果没有找到路径分隔符，则整个路径就是文件名
        strncpy(filename, path, size);
    } else {
        // 如果找到了路径分隔符，则文件名就是路径分隔符后面的部分
        strncpy(filename, pos + 1, size);
    }
    // 确保字符串以 NULL 终止
    filename[size - 1] = '\0';
}

int  ls_m(MYSQL *db, char* current_path, int netfd) {
    MYSQL *db = mysql_init(NULL);
    char *host = "localhost";
    char *user = "root";
    char *password = "xia";
    char *database = "tablex";
    MYSQL *ret = mysql_real_connect(db,host,user,password,database,0,NULL,0);

    if(ret == NULL){
    printf("Error: %s\n", mysql_error(db));
    return -1;
    }

    char filename[256];
    get_filename(current_path, filename, sizeof(filename));
    char query1[1024];
    snprintf(query1, sizeof(query1), "SELECT * FROM FileTable WHERE filename = '%s'", filename);

    int qret_1 = mysql_query(db,query1);
    if(qret_1 != 0){
    printf("Error: %s\n", mysql_error(db));
    return -1;
    }
    char id[4] = {0};
    MYSQL_ROW row;
    while ((row = mysql_fetch_row(result)) != NULL) {
        strcpy(id, row[0]);
    }

    char query2[1024];
    snprintf(query2, sizeof(query2), "SELECT * FROM FileTable WHERE pre_id = '%s'", id);
    int qret_2 = mysql_query(db,query2);
    if(qret_2 != 0){
    printf("Error: %s\n", mysql_error(db));
    return -1;
    }
    
    char ls_result[1024];
    MYSQL_ROW row;
    while ((row = mysql_fetch_row(result)) != NULL) {
        strcat(ls_result, row[1]);
        strcat(ls_result," ");
    }
    strcat(ls_result,"\n");

    int size;
    size = strlen(ls_result);
    send(netfd, size, sizeof(int), 0);
    send(netfd, ls_result, strlen(ls_result), 0);

    mysql_free_result(result);
    return 0;

}